package com.controller.ht;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.nutz.el.Parse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.common.ajax.AjaxRes;
import com.common.mybatis.Page;
import com.common.utils.Base64Util;
import com.common.utils.DateUtils;
import com.common.utils.PropertyUtil;
import com.common.utils.base.Const;
import com.common.utils.base.UuidUtil;
import com.controller.base.BaseController;
import com.entity.Appendix;
import com.entity.AppendixRelationship;
import com.entity.NewsColumn;
import com.service.AppendixRelationshipService;
import com.service.AppendixService;
import com.service.userIndustryRelationshipService;
/**
 * 上传工具
 */
@Controller
public class WebuploaderController extends BaseController<Object>{

	@Autowired
	private AppendixService appservice;
	@Autowired
	private AppendixRelationshipService apprpservice;
	@RequestMapping("/uploadFile")
    public void uploadFile(@RequestParam(value = "file", required = false) MultipartFile file,String base64File,
    		String FirstFileName,HttpServletResponse response, HttpServletRequest request) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		if(file==null){
			file=Base64Util.base64ToMultipart(base64File);
		}
		JSONObject json=new JSONObject();
		PrintWriter out = response.getWriter();
		logger.info("上传文件开始");
		try {  
			Map<String,String> uploadMap=PropertyUtil.getPropertyMap(Const.UPLOAD_CONFIG);
			String fileAllowSuffix=uploadMap.get("fileAllowSuffix");//允许文件规格
			String fileAllowSize=uploadMap.get("fileAllowSize");//允许文件大小
			String fileFilePath=uploadMap.get("fileFilePath");//允许文件大小
			String suffix = "";
			String FileNName = "";
			try {
				suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
				FileNName=file.getOriginalFilename();
			} catch (Exception e) {
				String[]  strs=FirstFileName.split(".");
				suffix=strs[1];
				FileNName=strs[0];
			}
			
			if(StringUtils.isNotBlank(fileAllowSuffix)){
				//获取文件后缀名	
		    	int length = fileAllowSuffix.indexOf(suffix.toLowerCase());
		        if(length == -1){
		        	json.put("res", Const.FAIL);
					json.put("resMsg", "请上传允许格式的文件");
					out.print(json.toString());
					return;
		        }
			}	    	
			long size = file.getSize();
			if(StringUtils.isNotBlank(fileAllowSize)){
				 long allowsize=Long.parseLong(fileAllowSize);
			        if(size > allowsize){
			        	json.put("res", Const.FAIL);
						json.put("resMsg", "超过上传文件大小限制");
						out.print(json.toString());
						return;
			        }	
			}   
	        String realPath=request.getSession().getServletContext().getRealPath("/");
	        String path=realPath+fileFilePath;
	        String fileName =DateUtils.getDate("yyyyMMdd")+ UuidUtil.get32UUID()+"."+suffix;  
	        File baseFile = new File(path);
			File targetFile = new File(baseFile, fileName);
			if(!baseFile.exists())baseFile.mkdirs();  
	        //保存  
            file.transferTo(targetFile);  
			Appendix app = new Appendix();
			app.setId(UuidUtil.get32UUID());
			app.setAppendixName(fileName);
			app.setAppendixFileName(FileNName);
			app.setAppendixSuffix(suffix);
			app.setAppendixSize(Long.toString(size));
			//路径
			app.setAppendixUrl(fileFilePath);
			app.setAppendixOtherUrl(path);
			app.setUploadTime(new Date());
			app.setDownloadCount(0);
			app.setAppendixState("正常");
			AppendixRelationship apprp = new AppendixRelationship();
			apprp.setId(UuidUtil.get32UUID());
			apprp.setAppendixId(app.getId());
			apprp.setAppendixClass(app.getAppendixSuffix());
			apprp.setRelationNo("0");
			apprp.setRelationTName("null");
			apprp.setUploadingPerson("admin");
			apprp.setUploadingTime(new Date());
			apprp.setRemark("无");
			apprp.setUrl(app.getAppendixUrl()+app.getAppendixName());
			appservice.insert(app);     
			apprpservice.insert(apprp);
        	json.put("res", Const.SUCCEED);
			json.put("saveUrl","/"+fileFilePath+fileName);
			json.put("apprpId",apprp.getId());
			json.put("resMsg", "上传成功");
			json.put("size", size);
			json.put("url", apprp.getUrl());
			out.print(json.toString());
			logger.info("上传文件结束，位置："+path);
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("上传文件出错",e);
		}		
    } 
	/**
	 * 分页查询
	 * @return
	 */
	@RequestMapping("/appendixFindByPage")
	@ResponseBody
	public AjaxRes appendixFindByPage(Appendix app,Page<Appendix> p){
		AjaxRes res = new AjaxRes();
		Page<Appendix> pageUis = appservice.findByPage(app, p);
		// 获得SimpleDateFormat类
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		for (int i = 0; i < pageUis.getResults().size(); i++) {
			pageUis.getResults().get(i).setUploadTimeToString(sf.format(pageUis.getResults().get(i).getUploadTime()));
		}
		res.setSucceed(pageUis, "数据获取成功");
		return res;
	}
	/**
	 * 下载附件需要传递路径
	 * @param fileurl
	 * @param session
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/downById")  
	public void getFile(String fileurl,  HttpSession session, HttpServletResponse response)
            throws IOException {
		System.out.println("==========="+fileurl);
        String basePath = session.getServletContext().getRealPath("/"); // 获取基本路径    
        if (null!=fileurl && !fileurl.equals("")) {
            /* 第一步:根据文件路径获取文件 */
            File file = new File(basePath + fileurl);
            if (file.exists()) { // 文件存在
                /* 第二步：根据已存在的文件，创建文件输入流 */
                InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
                /* 第三步：创建缓冲区，大小为流的最大字符数 */
                byte[] buffer = new byte[inputStream.available()]; // int available() 返回值为流中尚未读取的字节的数量
                /* 第四步：从文件输入流读字节流到缓冲区 */
                inputStream.read(buffer);
                /* 第五步： 关闭输入流 */
                inputStream.close();

                String fileName = file.getName();// 获取文件名
                response.reset();
                response.addHeader("Content-Disposition",
                        "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
                response.addHeader("Content-Length", "" + file.length());

                /* 第六步：创建文件输出流 */
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                /* 第七步：把缓冲区的内容写入文件输出流 */
                outputStream.write(buffer);
                /* 第八步：刷空输出流，并输出所有被缓存的字节 */
                outputStream.flush();
                /* 第九步：关闭输出流 */
                outputStream.close();

            } //end  if (file.exists())
        } else {
            return;
        }
    }
}
